package com.hnit;

import dev.langchain4j.community.model.dashscope.QwenEmbeddingModel;
import dev.langchain4j.data.embedding.Embedding;
import dev.langchain4j.model.output.Response;

import java.util.List;

public class RAG_App1 {
    public static void main(String[] args) {
        //1.文本向量化
        QwenEmbeddingModel qwenEmbeddingModel = QwenEmbeddingModel.builder()
                .apiKey(System.getenv("ALI_API_KEY"))
                .build();

        //文本向量化
        Response<Embedding> embed = qwenEmbeddingModel.embed("这是一只漂亮的小狗");
        System.out.println(embed.content().toString());//向量值
        System.out.println(embed.content().vector().length);//向量维度

        //1.相似度比较
        Embedding emb1 = qwenEmbeddingModel.embed("这是一只小狗").content();
        Embedding emb2 = qwenEmbeddingModel.embed("那是条狗").content();
        Embedding emb3 = qwenEmbeddingModel.embed("今天天气真好").content();

        double sim = cosineSimilarity(emb3.vectorAsList(), embed.content().vectorAsList());
        System.out.println("相似度：" + sim);
    }

    private static double cosineSimilarity(List<Float> a, List<Float> b) {
        if (a.size() != b.size()) {
            throw new IllegalArgumentException("向量维度不一致");
        }

        double dotProduct = 0.0;
        double normA = 0.0;
        double normB = 0.0;

        for (int i = 0; i < a.size(); i++) {
            double x = a.get(i);
            double y = b.get(i);
            dotProduct += x * y;
            normA += x * x;
            normB += y * y;
        }

        if (normA == 0.0 || normB == 0.0) return 0.0;

        return dotProduct / (Math.sqrt(normA) * Math.sqrt(normB));
    }
}
